<template>
  <div class="product-common-list">
    <AutofixScroll :height="height" @bottom="onBottom">
      <slot name="header"></slot>
      <div class="product-card-list">
        <div class="list-item" v-for="item in productList" :key="item.id">
          <ProductCard
            :img="item.url"
            :title="item.title"
            :price="item.price"
            :id="item.id"
          ></ProductCard>
        </div>
      </div>
      <div v-show="pageData.done" class="footer">没有更多了</div>
    </AutofixScroll>
  </div>
</template>

<script setup>
import { ref, onMounted, toRefs, watch } from "vue";
import AutofixScroll from "@/components/AutofixScroll/index";
import ProductCard from "@/components/ProductCard/index";
import { getProductList } from "@/api/product";
import { useToast } from "@/hooks/useToast";

const { loading, hideLoading } = useToast();

const props = defineProps({
  listApi: {
    type: String,
    default: "",
  },
  extParams: {
    type: Object,
    default: () => ({}),
  },
  height: {
    type: Number,
    default: 0,
  },
});
const { listApi, extParams } = toRefs(props);

const defaultPage = {
  pageSize: 8,
  pageNum: 0,
  total: 0,
  done: false,
};
const pageData = ref({ ...defaultPage });
const productList = ref([]);

const reset = () => {
  productList.value = [];
  pageData.value = { ...defaultPage };
};

const loadData = () => {
  if (pageData.value.done) return;
  loading();
  pageData.value.pageNum += 1;
  getProductList(listApi.value, {
    pageSize: pageData.value.pageSize,
    pageNo: pageData.value.pageNum,
    ...extParams.value,
  }).then((res) => {
    const list = res.records.map((item) => {
      return {
        id: item.id,
        title: item.name,
        price: item.price + "",
        url: item.imageList.length ? item.imageList[0] : "",
      };
    });
    productList.value.push(...list);
    pageData.value.total = res.total;
    pageData.value.done = pageData.value.total <= productList.value.length;
    hideLoading();
  });
};
watch(
  extParams,
  (val, oldVal) => {
    if (JSON.stringify(val) === JSON.stringify(oldVal)) return;
    reset();
    loadData();
    console.log("list props change", val, oldVal);
  },
  {
    deep: true,
    immediate: true,
  }
);

const onBottom = () => {
  loadData();
};
</script>

<style lang="scss" scoped>
.product-common-list {
  height: 100%;
  width: 100%;
  .product-card-list {
    display: flex;
    flex-wrap: wrap;
    .list-item {
      width: 47%;
      margin: 0 1.5% 16px 1.5%;
    }
  }
  .footer {
    padding: 10px 0;
    text-align: center;
    font-size: 12px;
    color: #777;
  }
}
</style>
